package my2Cents;

import java.awt.Container;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

import javax.swing.JFileChooser;
import javax.swing.JFrame;


public class Util_FILE {
	private static File mainFolder = new File("data");
	
	public static void checkMainFolder() {
		if(!mainFolder.exists()) {
			mainFolder.mkdir();
		}
	}
	
	public static String getFileType(String f) {
		int ext = f.lastIndexOf(".");
		return f.substring(ext+1);
	}
	
	public static String getFileType(File f) {
		return getFileType(f.getName());
	}
	
	public static String getFileName(String f) {
		int ext = f.lastIndexOf(".");
		int n = f.lastIndexOf('/');
		int n2 = f.lastIndexOf('\\');
		if(n2 > n) n=n2;
		if(n>0 && ext>0) {
			f = f.substring(n+1,ext);
		} else if(n>0) {
			f = f.substring(n+1,f.length());
		} else if(ext>0) {
			f = f.substring(0,ext);
		}
		return f;
	}
	
	public static void setMainFolder(String folder) {
		mainFolder = new File(folder);
	}
	
	public static String readData(File f) {
		BufferedReader reader = getFileReader(f);
		String line = new String();
		String out = new String();
		boolean isHeaderTxt = true;
		try {
			while ((line = reader.readLine()) != null){
				out = out + line + "\n";
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			Thread.sleep(20);
			reader.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return out;
	}
	
	public static boolean isFileType(File file, String type) {
		type = type.toLowerCase();
        String filename = file.getName().toLowerCase();
        return filename.endsWith(type) || file.isDirectory();
	}
	
	public static Vector<File> recursiveFind(String type, File start) {
		Vector<File> findings = new Vector<File>();
		if(start.isDirectory()) {
			File[] files = start.listFiles();
			for(int i=0; i<files.length; i++) {
				if (!files[i].isDirectory() && isFileType(files[i],type)) {
					findings.add(files[i]);
				}				
			}
			for(int i=0; i<files.length; i++) {
				if(files[i].isDirectory()) {
					findings.addAll(recursiveFind(type, files[i]));
				}
			}
		}
		return findings;
	}
	
	public static void writeKeyValues(File f, Vector<KeyValue> values) {
		BufferedWriter writer = getFileWriter(f);
		try {
			for(int i=0; i<values.size(); i++) {
				KeyValue v = values.get(i);
				writer.write(v.toString());
				writer.newLine();
			}
			writer.write("EndOfHeader");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			Thread.sleep(1000);
			writer.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static String fixSlashes(String s) {
		return s.replace('\\', '/');
	}
	
	public static Vector<KeyValue> readKeyValues(File f) {
		Vector<KeyValue> values = new Vector<KeyValue>();
		BufferedReader reader = getFileReader(f);
		String line = new String();
		boolean isHeaderTxt = true;
		try {
			while ((line = reader.readLine()) != null){
				if(line.equals("EndOfHeader")) {
					isHeaderTxt = false;
				}
				if(isHeaderTxt) {
					values.add(new KeyValue(line));
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			Thread.sleep(1000);
			reader.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return values;
	}
	
	public static boolean fileExists(String file) {
		File f = new File(mainFolder.getPath() + "\\" + file);
		return f.exists();
	}
	
	public static File openFile(String file, boolean createMissing) {
		File f = new File(mainFolder.getPath() + "\\" + file);
		if(f.exists() == false && createMissing == true) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return f;
	}
	
	public static String cleanFileName(String in) {
		String[] inc = in.toLowerCase().split("");
		String out = "";
		String[] allowedChars = Utility.aToz;
		for(int i=0; i<inc.length; i++) {
			for(int x=0; x<allowedChars.length; x++) {
				if(inc[i].equals(allowedChars[x])) {
					out+=inc[i];
				}
			}
		}
		return out;
	}
	
	public static BufferedReader getFileReader(File f) {
		FileReader fr;
		BufferedReader r = null;
		if(f.exists()) {
			try {
				fr = new FileReader(f);
				r = new BufferedReader(fr);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return r;
	}
	
	public static BufferedWriter getFileWriter(File f) {
		FileWriter fr;
		BufferedWriter r = null;
		if(f.exists()) {
			try {
				fr = new FileWriter(f);
				r = new BufferedWriter(fr);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return r;
	}
	
	public static File chooseFile(Container frame, boolean save, String filter, File dir) {
		checkMainFolder();
		if(!dir.exists()) {
			dir.mkdir();
		}
	    JFileChooser chooser = new JFileChooser(dir);
	    //chooser.addChoosableFileFilter(new MyFilter());
	    chooser.removeChoosableFileFilter(chooser.getFileFilter());
	    chooser.addChoosableFileFilter(new MyFilter(filter));

	    if(save) {
	    	chooser.setApproveButtonText("Save");
	    	chooser.setDialogTitle("Save");
	    }
	    
		// Show the dialog; wait until dialog is closed
	    int result = chooser.showOpenDialog(frame);
	    
	    // Determine which button was clicked to close the dialog
	    if(result == JFileChooser.APPROVE_OPTION) {
	    	File file = chooser.getSelectedFile();
	    	return file;
	    }
	    return null;
	}

}
	
class MyFilter extends javax.swing.filechooser.FileFilter {
	private String filtername = "dat";
	private String description = filtername;
	
	public MyFilter(String filtername) {
		this(filtername, "." + filtername);
	}
	
	public MyFilter(String filtername, String description) {
		this.filtername = filtername;
		this.description = description;
	}
	
    public boolean accept(File file) {
        String filename = file.getName().toLowerCase();
        return filename.endsWith(filtername) || file.isDirectory();
    
    }
    public String getDescription() {
        return description;
    }
}
